import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-02
 * Time: 20:29
 */
class MyTimerTask implements Comparable<MyTimerTask> {
    public Runnable runnable;   //要执行的任务
    public long time; //多久后执行

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
    public long getTime(){
        return time;
    }
    public void run(){
        runnable.run();
    }
    public MyTimerTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

}
public class MyTimer {
    public PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    public static Object locker = new Object();
    public MyTimer(){
        Thread t = new Thread(()->{
            while(true){
                synchronized (locker){
                    MyTimerTask task = queue.peek();
                    while(task == null){
                        try {
                            locker.wait();
                            task = queue.peek();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    long curTime = System.currentTimeMillis();
                    if(curTime >= task.getTime()){
                        task.run();
                        queue.poll();
                    }else{
                        try {
                            locker.wait(task.getTime() - curTime);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable, int delay){
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(runnable, delay);
            queue.add(myTimerTask);
            locker.notify();
        }


    }
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("hello 3000");
        }, 3000);
        myTimer.schedule(()->{
            System.out.println("hello 2000");
        }, 2000);
        myTimer.schedule(()->{
            System.out.println("hello 1000");
        }, 1000);
        Thread.sleep(4000);
        System.out.println("hello main");

    }
}


